import service from './service'
import { CONTENT_TYPE } from '@/constants'
import type { RawAxiosRequestHeaders } from 'axios'
import { useUserStoreWithOut } from '@/stores/modules/user'

type AxiosMethod = 'get' | 'post' | 'delete' | 'put'
type AxiosResponseType = 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream'

interface AxiosConfig {
    params?: any
    data?: any
    url?: string
    method?: AxiosMethod
    headers?: RawAxiosRequestHeaders
    responseType?: AxiosResponseType
}

const request = (option: AxiosConfig) => {
    const {url, method, params, data, headers, responseType} = option

    const userStore = useUserStoreWithOut()
    return service.request({
        url: url,
        method,
        params,
        data: data,
        responseType: responseType,
        headers: {
            'Content-Type': CONTENT_TYPE,
            [userStore.getTokenKey ?? 'Authorization']: userStore.getToken ?? '',
            ...headers
        }
    })
}

interface IResponse<T> {
    code: number
    data: T extends any ? T : T & any
}

export default {
    get: <T>(option: AxiosConfig) => {
        return request({method: 'get', ...option}) as Promise<IResponse<T>>
    },
    post: <T>(option: AxiosConfig) => {
        return request({method: 'post', ...option}) as Promise<IResponse<T>>
    },
    delete: <T>(option: AxiosConfig) => {
        return request({method: 'delete', ...option}) as Promise<IResponse<T>>
    },
    put: <T>(option: AxiosConfig) => {
        return request({method: 'put', ...option}) as Promise<IResponse<T>>
    },
    cancelRequest: (url: string | string[]) => {
        return service.cancelRequest(url)
    },
    cancelAllRequest: () => {
        return service.cancelAllRequest()
    }
}
